package com.home.fansea.test.executor;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

public class ForkJoinRecurisiveTask {
	//最大计算数
	private static final int MAX_THRESHOLD = 5;
	public static void main(String[] args) {
		//创建ForkJoinPool
		ForkJoinPool pool = new ForkJoinPool();
		//异步提交RecursiveTask任务
		ForkJoinTask<Integer> forkJoinTask = pool.submit(new CalculatedRecurisiveTask(0,100));
		try {
			//根据返回类型获取返回值
			Integer result = forkJoinTask.get();
			System.out.println("结果为："+result);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	private static class CalculatedRecurisiveTask extends RecursiveTask<Integer>{
		private int start;
		private int end;
		public CalculatedRecurisiveTask(int start, int end) {
			this.start = start;
			this.end = end;
		}
		@Override
		protected Integer compute() {
			//判断计算范围，如果小于等于5，那么一个线程计算就够了，否则进行分割
			if ((end-start)<=5) {
				return IntStream.rangeClosed(start, end).sum();
			}else {
				//任务分割:将start一直加到end，当超过5计算量大就分开线程计算（分而治之这是ForkJoin的核心思想）
				int middle = (end+start)/2;
				CalculatedRecurisiveTask task1 = new CalculatedRecurisiveTask(start,middle);
				CalculatedRecurisiveTask task2 = new CalculatedRecurisiveTask(middle+1,end);
				//执行
				task1.fork();
				task2.fork();
				//等待返回结果
				return task1.join()+task2.join();
			}
		}
	}
}
